<?php
namespace app\client\controller;
use app\common\lib\GatewayCurl;

class Charge extends Base {
    
    public function __construct() {
        parent::__construct();
    }
    
    //充电
    public function charge() {
        if($this->noLogin()) {
            return $this->noLoginReturn();
        }
        
        $params = request()->post();
        
        $deviceNo = isset($params['deviceNo']) ? intval($params['deviceNo']) : 0;
        if($deviceNo <= 0) {
            return errorResult();
        }
        
        $portId = isset($params['portId']) ? intval($params['portId']) : 0; //端口id
        if($portId <= 0) {
            return errorResult();
        }
        
        $quantity = isset($params['quantity']) ? floatval($params['quantity']) : 0; //充多少小时/度
        if($quantity <= 0) {
            return errorResult();
        }
        
        unset($params);
        
        $device = model('Device')->findOne(['device_no' => $deviceNo], ['device_id', 'sim_iccid', 'gateway', 'agent_id', 'store_id', 'lock_status', 'heart_time', 'price_id']);
        if(empty($device) || empty($device['price_id'])) {
            return errorResult('设备不存在或者未支持扫码使用');
        }
        
        $time = time();
        if($device['lock_status'] == 1) {
            return errorResult('设备已停用');
        }
        
        if(($device['heart_time'] + 300) < $time) {
            return errorResult('设备已掉线');
        }
        
        $portModel = model('DevicePort');
        
        //查看端口
        $port = $portModel->findOne(['port_id' => $portId], ['status', 'device_id', 'port_no']);
        if(empty($port) || $port['device_id'] != $device['device_id']){
            return errorResult('设备已掉线');
        }
        
        if($port['status'] != 0){
            return errorResult('端口被占用或已损坏');
        }
        
        
        //查询价格套餐
        $payPrice = model('ChargePrice')->findOne(['price_id' => $device['price_id']], ['options', 'charge_unit', 'charge_type']);
        if(empty($payPrice) || empty($payPrice['options'])){
            return errorResult('设备未支持扫码使用');
        }
        
        $amount = 0;
        
        $options = $payPrice['options'];
        if(!is_array($options)) {
            $options = json_decode($options, true);
        }
        $isPrice = false;
        foreach ($options as $option) {
            if($option['q'] == $quantity){
                $amount = $option['a'];
                
                if($payPrice['charge_type'] == 1) { //计时的
                    $quantity *= 60; //转成分钟
                }
                
                $isPrice = true;
                break;
            }
        }
        
        if(!$isPrice){ //未找到对应的价格
            return errorResult();
        }
        
        $orderNo = getOrderNo($this->userid);
        $orderData = [
            'order_no' => $orderNo,
            'user_id' => $this->userid,
            'device_id' => $device['device_id'],
            'device_no' => $deviceNo,
            'pay_to' => 1,
            'port_no' => $port['port_no'],
            'charge_quantity' => $quantity,
            'amount' => $amount,
            'charge_type' => $payPrice['charge_type'],
            'charge_unit' => $payPrice['charge_unit'],
            'create_time' => time()
        ];
        
        unset($payPrice);
        
        if($device['agent_id'] > 0){ //有代理
            //查询代理商是不是特约代理商
            $agent = model('Agent')->findOne(['agent_id' => $device['agent_id']], ['agent_type', 'mch_id', 'mch_key']);
            if($agent['agent_type'] == 2){ //特约代理商
                $orderData['pay_to'] = 2;
            }
            
            $orderData['agent_id'] = $device['agent_id'];
            
            if($device['store_id'] > 0){ //有门店
                $orderData['profit_rate'] = model('Store')->where(['store_id' => $device['store_id']])->value('profit_rate');
                $orderData['store_id'] = $device['store_id'];
            }
        }
        
        
        $orderModel = model('ChargeOrder');
        
        $orderModel->startTrans();
        
        try {
            
            $orderId = $orderModel->add($orderData);
            if(!$orderId){
                $orderModel->rollback();
                return errorResult();
            }
            
            $rs = $portModel->modify(['port_id' => $portId], ['current_order_id' => $orderId]);
            if($rs === false) {
                $orderModel->rollback();
                return errorResult();
            }
            
            //发起支付
            $wxPay = new \app\client\wxpay\WxPayUnifiedOrder(session('user')['openid']);
            if($orderData['pay_to'] == 2){ //特约代理商
                $wxPay->setMerchantId($agent['mch_id']);
                $wxPay->setMerchantKey($agent['mch_key']);
            }
            
            $wxOrderParams = [
                'body' => '测试的支付',
                'order_no' => $orderNo,
                'amount' => $amount,
                'notify_url' => 'charge'
            ];
            
            if($orderData['pay_to'] == 2){ //如果是特约代理商，把代理商id加到附加数据里
                $wxOrderParams['attach'] = json_encode(['count' => $orderData['agent_id'] * 1314 + 325, 'id' => floor(time() / 1000)]);
            }
            
            $wxPay->setOrder($wxOrderParams);
            
            $payParams = $wxPay->getParams(); //获取发起支付的参数
            
            if($payParams['err']){
                $orderModel->rollback();
                return errorResult();
            }
            
            $orderModel->commit();
            
            return successResult(['wxparam' => $payParams['params'], 'order_id' => $orderId]);
            
            
        } catch (\Exception $e) {
            $orderModel->rollback();
            return errorResult($e->getMessage());
        }
    }
    
    public function chargeResult() {
        if($this->noLogin()) {
            return $this->noLoginReturn();
        }
        
        $orderId = request()->post('id', 0, 'intval');
        if($orderId <= 0) {
            return errorResult('cc');
        }
        $order = model('ChargeOrder')->findOne(['order_id' => $orderId], ['user_id', 'status']);
        if(empty($order) || $order['user_id'] != $this->userid) {
            return errorResult('dd');
        }
        
        return successResult(['status' => $order['status']]);
    }
    
    public function extendChargeInfo() {
        if($this->noLogin()) {
            return $this->noLoginReturn();
        }
        
        $orderId = request()->get('id', 0, 'intval');
        if($orderId <= 0) {
            return errorResult();
        }
        
        $order = model('ChargeOrder')->findOne(['order_id' => $orderId], ['order_no', 'device_id', 'device_no', 'port_no', 'charge_type', 'start_time', 'charge_quantity']);
        if(empty($order)) {
            return errorResult();
        }
        
        $port = model('DevicePort')->findOne(['current_order_id' => $orderId], ['surplus_time', 'surplus_energy', 'power']);
        if(empty($port)) {
            return errorResult();
        }
        
        $order['data'] = $port;
        
        $priceId = model('Device')->where(['device_id' => $order['device_id']])->value('price_id');
        $chargePrice = model('ChargePrice')->findOne(['price_id' => $priceId], ['options', 'charge_type']);
        if(empty($chargePrice) || $chargePrice['charge_type'] != $order['charge_type']) {
            return errorResult('本次充电不支持增加充电');
        }
        
        return successResult(['order' => $order, 'charge_price' => $chargePrice, 'current_time' => time()]);
    }
    
    //增加充电时间
    public function extendCharge() {
        if($this->noLogin()) {
            return $this->noLoginReturn();
        }
        
        $params = request()->post();
        
        $orderId = isset($params['orderId']) ? intval($params['orderId']) : 0;
        if($orderId <= 0) {
            return errorResult('cc');
        }
        
        $quantity = isset($params['quantity']) ? floatval($params['quantity']) : 0; //充多少小时
        if($quantity <= 0) {
            return errorResult();
        }
        
        $order = model('ChargeOrder')->findOne(['order_id' => $orderId], ['user_id', 'pay_to', 'agent_id', 'charge_quantity', 'start_time', 'status', 'device_id', 'port_no']);
        if(empty($order) || $order['user_id'] != $this->userid){
            return errorResult('caaa');
        }
        
        if($order['status'] != 1){
            return errorResult('该订单已结束充电');
        }
        
        $time = time();
        
        /* if(($order['start_time'] + $order['charge_quantity'] * 60 + 120) <= $time){
            return errorResult('订单即将结束充电，不能增加充电时间');
        } */
        
        $device = model('Device')->findOne(['device_id' => $order['device_id']], ['sim_iccid', 'gateway', 'price_id']);
        
        //查询价格套餐
        $payPrice = model('ChargePrice')->findOne(['price_id' => $device['price_id']], ['options', 'charge_type']);
        if(empty($payPrice)){
            return errorResult('设备未开始使用');
        }
        
        $amount = 0;
        
        $options = json_decode($payPrice['options'], true);
        $isPrice = false;
        foreach ($options as $option) {
            if($option['q'] == $quantity){
                $amount = $option['a'];
                
                if($payPrice['charge_type'] == 1) { //计时的
                    $quantity *= 60; //转成分钟
                }

                $isPrice = true;
                break;
            }
        }
        
        if(!$isPrice){
            return errorResult();
        }
        
        if($order['pay_to'] == 2){
            $agent = model('Agent')->findOne(['agent_id' => $order['agent_id']], ['mch_id', 'mch_key']);
        }
        
        
        
        $orderNo = getOrderNo($this->userid);
        $orderData = [
            'order_no' => $orderNo,
            'user_id' => $this->userid,
            'extend_quantity' => $quantity,
            'charge_order_id' => $orderId,
            'amount' => $amount,
            'create_time' => $time
        ];
        
        $orderModel = model('ExtendChargeOrder');
        
        $orderModel->startTrans();
        
        try {
            $orderId = $orderModel->add($orderData);
            
            if(!$orderId){
                $orderModel->rollback();
                return errorResult();
            }
            
            //发起支付
            $wxPay = new \app\client\wxpay\WxPayUnifiedOrder(session('user')['openid']);
            if($order['pay_to'] == 2){
                $wxPay->setMerchantId($agent['mch_id']);
                $wxPay->setMerchantKey($agent['mch_key']);
            }
            
            $wxOrderParams = [
                'body' => '增加测试的支付',
                'order_no' => $orderNo,
                'amount' => $amount,
                'notify_url' => 'addcharge'
            ];
            
            if($order['pay_to'] == 2){
                $wxOrderParams['attach'] = json_encode(['count' => $order['agent_id'] * 1314 + 325, 'id' => floor(time() / 1000)]);
            }
            
            $wxPay->setOrder($wxOrderParams);
            
            $payParams = $wxPay->getParams(); //获取发起支付的参数
            
            if($payParams['err']){
                $orderModel->rollback();
                return errorResult('abc');
            }
            
            $orderModel->commit();
            
            return successResult(['wxparam' => $payParams['params'], 'order_id' => $orderId]);
            
            
        } catch (\Exception $e) {
            $orderModel->rollback();
            return errorResult();
        }
    }
    
    
    public function extendChargeResult() {
        if($this->noLogin()) {
            return $this->noLoginReturn();
        }
        
        $orderId = request()->post('id', 0, 'intval');
        if($orderId <= 0) {
            return errorResult('cc');
        }
        $order = model('ExtendChargeOrder')->findOne(['order_id' => $orderId], ['user_id', 'status']);
        if(empty($order) || $order['user_id'] != $this->userid) {
            return errorResult('dd');
        }
        
        return successResult(['status' => $order['status']]);
    }
    
    //停止充电
    public function stopCharge() {
        if($this->noLogin()) {
            return $this->noLoginReturn();
        }
        
        $orderId = request()->post('id', 0, 'intval');
        if($orderId <= 0) {
            return errorResult('cc');
        }
        $order = model('ChargeOrder')->findOne(['order_id' => $orderId], ['user_id', 'port_no', 'device_id', 'status']);
        if(empty($order) || $order['user_id'] != $this->userid) {
            return errorResult('dd');
        }
        
        $portNo = $order['port_no'];
        $device = model('Device')->findOne(['device_id' => $order['device_id']], ['gateway', 'sim_iccid']);
        
        $curl = new GatewayCurl();
        $result = $curl->send('stopCharge', ['deviceId' => $device['sim_iccid'], 'portNo' => $portNo]);
        if($result['success'] == false) {
            return errorResult();
        }
        
        return successResult();
    }

}

















